const fs = require('fs')
const path = require('path')

module.exports = options => ({
  /**
   * 公共上传
   * @returns 文件地址
   */
  async upload () {
    const { ctx, config, } = options
    const uploadBasePath = 'static/public/upload'
    // 获取上传文件
    const file = ctx.request.files.file
    // 创建读取文件流
    const reader = fs.createReadStream(file.path)
    // 创建文件夹
    const folderName = ctx.helper.dateFormat(Date.now())
    const dirName = path.join(config.baseDir, uploadBasePath, folderName)
    if (!fs.existsSync(dirName)) fs.mkdirSync(dirName)
    // 生成文件名
    const extName = path.extname(file.name) // 扩展名
    const name = file.name.split(extName)[0] // 原始文件名
    const filename = name + '_' +  ctx.helper.dateFormat(Date.now(), 'YYYYMMDDhhmmss') + extName.toLowerCase()
    // 生成保存路径
    const target = path.join(dirName, filename)
    // 创建写入文件流
    const writeStream = fs.createWriteStream(target)
    try {
      // 写入文件
      await reader.pipe(writeStream)
    } catch (error) {
      throw(error)
    }
    const url = `http://${ctx.host}/public/upload/${folderName}/${filename}`

    return url
  }
})